﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Backend.JYD.Business;

namespace Backend.JYD.RunTime.Attribute
{
    public class AuthorityFilter : ActionFilterAttribute
    {
        private string[] AuthCodes = null;
        private bool IsAjax = false;
        private AuthManager manager = new AuthManager();

        public AuthorityFilter(params string[] codes) : this(false, codes) { }
        public AuthorityFilter(bool ajax, params string[] codes)
        {
            this.AuthCodes = codes;
            this.IsAjax = ajax;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var empInfo = SessionMgr.GetEmpInfoFromSession(filterContext.HttpContext);
            if (empInfo == null || empInfo.EmpId <= 0)
            {
                filterContext.Result = this.FaildResult("需要登录。", "/home/loginout");
                return;
            }
            var authorityInfoes = manager.GetEmpAuthorityInfoesByEmpId(empInfo.EmpId);
            if (authorityInfoes == null || authorityInfoes.Count <= 0)
            {
                filterContext.Result = this.FaildResult("权限不足。", "/home/loginout");
                return;
            }

            if (authorityInfoes != null && authorityInfoes.Count > 0 && authorityInfoes.Exists(p => this.AuthCodes.Contains(p.Code)))
            {
                base.OnActionExecuting(filterContext);
                return;
            }
            filterContext.Result = this.FaildResult("权限不足。", "/home/loginout");
        }

        private ActionResult FaildResult(string msg, string url)
        {
            if (this.IsAjax)
            {
                var js = new JsonResult();
                js.Data = new { code = false, msg = msg };
                return js;
            }
            else
            {
                return new RedirectResult(url);
            }
        }
    }
}
